package com.yuanlun.elasticsearch.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName StarController
 * @Description TODO
 * @Author zxw
 * @DATE 2021/5/6 14:13
 * Version 1.0
 **/
@RestController
@RequestMapping("/star")
@CrossOrigin(origins = "*")
public class StarController {
    @Resource
    private  RestHighLevelClient elasticsearchClient;


    @GetMapping("/autoComplete")
    public Object autoComplete(String term) throws IOException {
        Request request = new Request("GET", "stars/_search");

        request.setJsonEntity(String.format("{" +
                "  \"_source\": false,\n" +
                "  \"suggest\": {\n" +
                "    \"star_name_suggest\": {\n" +
                "     \"prefix\":\"%s\",\n" +
                "      \"completion\":{\n" +
                "        \"field\":\"name\",\n" +
                "        \"size\":10,\n" +
                "        \"skip_duplicates\":true\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}", term));
        Response response = elasticsearchClient.getLowLevelClient().performRequest(request);
        String jsonString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        JSONArray suggests = jsonObject.getJSONObject("suggest").getJSONArray("star_name_suggest");
        JSONArray options = suggests.getJSONObject(0).getJSONArray("options");
        List<String> results=new ArrayList<>();
        for (int i = 0; i < options.size(); i++) {
            JSONObject opt = options.getJSONObject(i);
            results.add(opt.getString("text"));
        }
        return results;
    }
}
